class TCPOctetStream { }
class TCPState {
    transmit(tcpCon: TCPConnection, tcpOS: TCPOctetStream): void { }
    activeOpen(tcpCon: TCPConnection): void { }
    passiveOpen(tcpCon: TCPConnection): void { }
    close(tcpCon: TCPConnection): void { }
    send(tcpCon: TCPConnection): void { }
    acknowledge(tcpCon: TCPConnection): void { console.log('确认接收'); }
    sycchronize(tcpCon: TCPConnection): void { }
    changeState(tcpCon: TCPConnection, tcpState: TCPState) {
        tcpCon.changeState(tcpState)
    }
}

class TCPConnection {
    declare private _state: TCPState
    constructor() {
        this._state = TCPClosed.instance()
    }
    transmit(): void {
        this._state.transmit(this, new TCPOctetStream())
    }
    activeOpen(): void {
        this._state.activeOpen(this)
    }
    passiveOpen(): void {
        this._state.passiveOpen(this)
    }
    close(): void {
        this._state.close(this)
    }
    send(): void {
        this._state.send(this)
    }
    acknowledge(): void {
        this._state.acknowledge(this)
    }
    sycchronize(): void {
        this._state.sycchronize(this)
    }
    processOctet(tcpOS: TCPOctetStream) {
        console.log("处理数据流");
    }
    changeState(tcpState: TCPState) {
        this._state = tcpState
        console.log('连接状态为：' + this._state.constructor.name);
    }
}
class TCPEstablished extends TCPState {
    private static declare _instance: TCPEstablished
    static instance() {
        if (!this._instance) {
            this._instance = new TCPEstablished()
        }
        return this._instance
    }
    transmit(tcpCon: TCPConnection, tcpOS: TCPOctetStream): void {
        tcpCon.processOctet(tcpOS)
    }
    close(tcpCon: TCPConnection): void {
        // send PIN, receive ACK of FIN
        this.changeState(tcpCon, TCPListen.instance())
    }
}

class TCPListen extends TCPState {
    private static declare _instance: TCPListen
    static instance() {
        if (!this._instance) {
            this._instance = new TCPListen()
        }
        return this._instance
    }
    send(tcpCon: TCPConnection): void {
        // send SYN, receiv e SYN, ACK , etc.
        this.changeState(tcpCon, TCPEstablished.instance())
    }
}
class TCPClosed extends TCPState {
    private static declare _instance: TCPClosed
    static instance() {
        if (!this._instance) {
            this._instance = new TCPClosed()
        }
        return this._instance
    }
    activeOpen(tcpCon: TCPConnection): void {
        // send SYN, receive SYN, ACK, etc.
        this.changeState(tcpCon, TCPEstablished.instance())
    }
    passiveOpen(tcpCon: TCPConnection): void {
        this.changeState(tcpCon, TCPListen.instance())
    }
}


///演示

//创建TCP连接，它会初始化为TCPClosed状态
const connect = new TCPConnection()
//主动打开连接，状态更改为TCPEstablished
connect.activeOpen()
//数据传输
connect.transmit()
//发送数据
connect.send()
//确认收到的数据
connect.acknowledge()
//关闭连接。
connect.close()
